package department

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/hugozhu/godingtalk"
	"myschools.me/dingtalk/config"
)

//ListHandler 所有部门列表
func ListHandler(c *gin.Context) {
	client := godingtalk.NewDingTalkClient(config.Dingtalk.AppKey, config.Dingtalk.AppSecret)
	client.RefreshAccessToken()
	data, err := client.DepartmentList()
	if err != nil {
		fmt.Println(err.Error())
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": data,
	})
}

//DetailHandler 部门详情
func DetailHandler(c *gin.Context) {
	idstr := strings.TrimLeft(c.Param("id"), "/")
	id, err := strconv.Atoi(idstr)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}
	client := godingtalk.NewDingTalkClient(config.Dingtalk.AppKey, config.Dingtalk.AppSecret)
	client.RefreshAccessToken()
	data, err := client.DepartmentDetail(id)
	if err != nil {
		fmt.Println(err.Error())
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": data,
	})
}

//UserlistHandler 部门成员列表
func UserlistHandler(c *gin.Context) {
	idstr := c.Query("id")
	id, err := strconv.Atoi(idstr)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	offsetstr := c.Query("offset")
	offset, err := strconv.Atoi(offsetstr)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	sizestr := c.Query("size")
	size, err := strconv.Atoi(sizestr)
	if err != nil {
		c.AbortWithStatus(http.StatusBadRequest)
		return
	}

	client := godingtalk.NewDingTalkClient(config.Dingtalk.AppKey, config.Dingtalk.AppSecret)
	client.RefreshAccessToken()
	data, err := client.UserList(id, offset, size)
	if err != nil {
		c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"data": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data": data,
	})
}
